#pragma once
#include <iostream>
#include "Socket.hpp"
#include <sys/select.h>
#include "Log.hpp"
#include <algorithm>
using namespace std;

static const uint16_t defaultport = 8888;
static const int fd_num_max = (sizeof(fd_set) * 8);
int defaultfd = -1;
Log lg;
//缺点
/*
1. 等待的fd是有上限的
2. 输入输出型参数比较多，数据拷贝的频率比较高
3. 输入输出型参数比较多，每次都要对关心的fd进行事件重置
4. 用户层，使用第三方数组管理用户的fd，用户层需要很多次遍历，内核中检测fd事件就绪，也要遍历
*/
class SelectServer
{
public:
    SelectServer(uint16_t port = defaultport)
        : _port(port)
    {
        for (int i = 0; i < fd_num_max; i++)
        {
            fd_array[i] = defaultfd;
        }
    }

    bool Init()
    {
        _listensock.Socket();
        _listensock.Bind(_port);
        _listensock.Listen();
        return true;
    }

    void Accepter()
    {
        // 我们的连接事件就绪了
        std::string clientip;
        uint16_t clientport = 0;
        int sock = _listensock.Accept(&clientip, &clientport); // 会不会阻塞在这里？不会
        if (sock < 0)
        {
            return;
        }
        lg(Info, "accept success, %s:%d, sock fd:%d", clientip.c_str(), clientport, sock);

        // sock添加到fd_array[]
        int pos = 1;
        for (; pos < fd_num_max; pos++)
        {
            if (fd_array[pos] != defaultfd)
                continue;
            else
                break;
        }
        if (pos == fd_num_max)
        {
            lg(Warning, "server is full, close %d now!", sock);
            close(sock);
        }
        else
        {
            fd_array[pos] = sock;
            // PrintFd();
        }
    }

    void Recver(int fd,int pos)
    {
        char buffer[1024];
        ssize_t n = read(fd, buffer, sizeof(buffer) - 1); // bug?
        if (n > 0)
        {
            buffer[n] = 0;
            cout << "get a message: " << buffer << endl;
        }
        else if (n == 0)
        {
            lg(Info, "client quit, me too, close fd is : %d ", fd);
            close(fd);
            fd_array[pos] = defaultfd; // 本质是从select中移除
        }
        else
        {
            lg(Warning, "recv error, fd is : %d", fd);
            close(fd);
            fd_array[pos] = defaultfd; // 本质是从select中移除
        }
    }

    void Dispatcher(fd_set &rfds)
    {
        for (int i = 0; i < fd_num_max; i++)
        {
            int fd = fd_array[i];
            if (fd = defaultfd)
                continue;
            if (FD_ISSET(fd, &rfds))
            {
                if (fd = _listensock.Fd()) // 获取新链接
                {
                    Accepter();
                }
                else // 读文件就绪
                {
                    Recver(fd,i);
                }
            }
        }
    }

    void Start()
    {

        // 多路转接不直接用accept，检测并获取listensock上面的事件，新连接到来，等价于读事件就绪
        int listensock = _listensock.Fd();
        fd_array[0] = listensock;

        while (true)
        {
            fd_set rfds;
            FD_ZERO(&rfds);
            int maxfd = fd_array[0];
            for (int i = 0; i < fd_num_max; i++)
            {
                if (fd_array[i] == defaultfd)
                {
                    continue;
                }
                FD_SET(fd_array[i], &rfds);
                maxfd = max(maxfd, fd_array[i]);
                lg(Info, "maxfd update is :%d", maxfd);
            }
            // 只关心读事件

            struct timeval timeout = {1, 0};
            // rfds是一个输入输出型参数，当我们要关心1111 1111：0~7好文件描述符时，
            // 输出0000 0001只有一个文件描述符就绪，甚至没有，而原文被覆盖。这就需要我们每次开始要重复设置rfds,借助
            // 辅助数组
            int n = select(maxfd + 1, &rfds, nullptr, nullptr, &timeout);

            switch (n)
            {
            case 0:
                cout << "time out, timeout: " << timeout.tv_sec << "." << timeout.tv_usec << endl;
                break;
            case -1:
                cerr << "select error" << endl;
                break;
            default:
                cout << "OK" << endl;
                // 有事件就绪了
                Dispatcher(rfds);
                break;
            }
        }
    }

    void PrintFd()
    {
        cout << "online fd list: ";
        for (int i = 0; i < fd_num_max; i++)
        {
            if (fd_array[i] == defaultfd)
                continue;
            cout << fd_array[i] << " ";
        }
        cout << endl;
    }

    ~SelectServer()
    {
        _listensock.Close();
    }

private:
    Sock _listensock;
    uint16_t _port;
    int fd_array[fd_num_max];
};